<template>
  <div class="contract-list-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>
          <el-icon><Document /></el-icon>
          合同管理
        </h2>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>合同管理</el-breadcrumb-item>
          <el-breadcrumb-item>合同列表</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleCreate">
          <el-icon><Plus /></el-icon>
          新建合同
        </el-button>
        <el-button @click="handleImport">
          <el-icon><Upload /></el-icon>
          导入
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
            <el-icon><Document /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.total }}</div>
            <div class="stat-label">合同总数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
            <el-icon><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.pending }}</div>
            <div class="stat-label">待审批</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
            <el-icon><CircleCheck /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.active }}</div>
            <div class="stat-label">执行中</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
            <el-icon><Warning /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ statistics.expiring }}</div>
            <div class="stat-label">即将到期</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索筛选 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="合同编号">
          <el-input v-model="searchForm.code" placeholder="请输入合同编号" clearable />
        </el-form-item>
        <el-form-item label="合同名称">
          <el-input v-model="searchForm.name" placeholder="请输入合同名称" clearable />
        </el-form-item>
        <el-form-item label="合同类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option label="销售合同" value="sales" />
            <el-option label="采购合同" value="purchase" />
            <el-option label="服务合同" value="service" />
            <el-option label="租赁合同" value="lease" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="合同状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="草稿" value="draft" />
            <el-option label="待审批" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已驳回" value="rejected" />
            <el-option label="执行中" value="active" />
            <el-option label="已完成" value="completed" />
            <el-option label="已终止" value="terminated" />
          </el-select>
        </el-form-item>
        <el-form-item label="签订日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><RefreshLeft /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 合同列表 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>合同列表</span>
          <div class="header-actions">
            <el-button text @click="handleBatchDelete" :disabled="selectedRows.length === 0">
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
            <el-button text @click="handleBatchExport" :disabled="selectedRows.length === 0">
              <el-icon><Download /></el-icon>
              批量导出
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="tableData"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        stripe
        border
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="合同编号" width="150" fixed>
          <template #default="{ row }">
            <el-link type="primary" @click="handleView(row)">{{ row.code }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="合同名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="type" label="合同类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeColor(row.type)">{{ getTypeName(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="partyA" label="甲方" width="150" show-overflow-tooltip />
        <el-table-column prop="partyB" label="乙方" width="150" show-overflow-tooltip />
        <el-table-column prop="amount" label="合同金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount">¥{{ formatAmount(row.amount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="signDate" label="签订日期" width="120" />
        <el-table-column prop="startDate" label="开始日期" width="120" />
        <el-table-column prop="endDate" label="结束日期" width="120">
          <template #default="{ row }">
            <span :class="{ 'text-danger': isExpiringSoon(row.endDate) }">
              {{ row.endDate }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusColor(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <el-button text type="primary" size="small" @click="handleView(row)">
              <el-icon><View /></el-icon>
              查看
            </el-button>
            <el-button text type="primary" size="small" @click="handleEdit(row)" v-if="canEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button text type="warning" size="small" @click="handleApproval(row)" v-if="canApprove(row)">
              <el-icon><Check /></el-icon>
              审批
            </el-button>
            <el-button text type="danger" size="small" @click="handleDelete(row)" v-if="canDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Document, Plus, Upload, Download, Clock, CircleCheck, Warning,
  Search, RefreshLeft, Delete, View, Edit, Check
} from '@element-plus/icons-vue'

const router = useRouter()

// 统计数据
const statistics = reactive({
  total: 156,
  pending: 23,
  active: 89,
  expiring: 12
})

// 搜索表单
const searchForm = reactive({
  code: '',
  name: '',
  type: '',
  status: '',
  dateRange: []
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])

// 模拟数据
const mockData = [
  {
    id: 1,
    code: 'CT2024001',
    name: '软件开发服务合同',
    type: 'service',
    partyA: '某科技有限公司',
    partyB: '某信息技术公司',
    amount: 500000,
    signDate: '2024-01-15',
    startDate: '2024-02-01',
    endDate: '2024-12-31',
    status: 'active'
  },
  {
    id: 2,
    code: 'CT2024002',
    name: '办公设备采购合同',
    type: 'purchase',
    partyA: '某贸易有限公司',
    partyB: '某电子商务公司',
    amount: 120000,
    signDate: '2024-02-20',
    startDate: '2024-03-01',
    endDate: '2024-05-31',
    status: 'completed'
  },
  {
    id: 3,
    code: 'CT2024003',
    name: '产品销售合同',
    type: 'sales',
    partyA: '某制造有限公司',
    partyB: '某商贸公司',
    amount: 800000,
    signDate: '2024-03-10',
    startDate: '2024-03-15',
    endDate: '2024-11-30',
    status: 'active'
  },
  {
    id: 4,
    code: 'CT2024004',
    name: '办公楼租赁合同',
    type: 'lease',
    partyA: '某物业管理公司',
    partyB: '某咨询有限公司',
    amount: 360000,
    signDate: '2024-01-05',
    startDate: '2024-02-01',
    endDate: '2025-01-31',
    status: 'active'
  },
  {
    id: 5,
    code: 'CT2024005',
    name: '市场推广服务合同',
    type: 'service',
    partyA: '某广告传媒公司',
    partyB: '某互联网公司',
    amount: 250000,
    signDate: '2024-04-01',
    startDate: '2024-04-10',
    endDate: '2024-10-10',
    status: 'pending'
  }
]

// 获取列表数据
const fetchList = () => {
  loading.value = true
  
  // 模拟API请求
  setTimeout(() => {
    tableData.value = mockData
    pagination.total = mockData.length
    loading.value = false
  }, 500)
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchList()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    code: '',
    name: '',
    type: '',
    status: '',
    dateRange: []
  })
  handleSearch()
}

// 新建
const handleCreate = () => {
  router.push('/contract/create')
}

// 查看
const handleView = (row) => {
  router.push(`/contract/detail/${row.id}`)
}

// 编辑
const handleEdit = (row) => {
  router.push(`/contract/edit/${row.id}`)
}

// 审批
const handleApproval = (row) => {
  router.push(`/contract/approval?id=${row.id}`)
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除合同"${row.name}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('删除成功')
    fetchList()
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 条合同吗？`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('批量删除成功')
    fetchList()
  })
}

// 导入
const handleImport = () => {
  ElMessage.info('导入功能开发中')
}

// 导出
const handleExport = () => {
  ElMessage.info('正在导出...')
  setTimeout(() => {
    ElMessage.success('导出成功')
  }, 1000)
}

// 批量导出
const handleBatchExport = () => {
  ElMessage.info('正在导出选中的合同...')
  setTimeout(() => {
    ElMessage.success('导出成功')
  }, 1000)
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页变化
const handleSizeChange = () => {
  fetchList()
}

const handlePageChange = () => {
  fetchList()
}

// 工具函数
const formatAmount = (amount) => {
  return amount.toLocaleString('zh-CN', { minimumFractionDigits: 2 })
}

const getTypeName = (type) => {
  const typeMap = {
    sales: '销售合同',
    purchase: '采购合同',
    service: '服务合同',
    lease: '租赁合同',
    other: '其他'
  }
  return typeMap[type] || type
}

const getTypeColor = (type) => {
  const colorMap = {
    sales: 'success',
    purchase: 'warning',
    service: 'primary',
    lease: 'info',
    other: ''
  }
  return colorMap[type] || ''
}

const getStatusName = (status) => {
  const statusMap = {
    draft: '草稿',
    pending: '待审批',
    approved: '已通过',
    rejected: '已驳回',
    active: '执行中',
    completed: '已完成',
    terminated: '已终止'
  }
  return statusMap[status] || status
}

const getStatusColor = (status) => {
  const colorMap = {
    draft: 'info',
    pending: 'warning',
    approved: 'success',
    rejected: 'danger',
    active: 'primary',
    completed: '',
    terminated: 'danger'
  }
  return colorMap[status] || ''
}

const isExpiringSoon = (endDate) => {
  if (!endDate) return false
  const days = Math.ceil((new Date(endDate) - new Date()) / (1000 * 60 * 60 * 24))
  return days <= 30 && days >= 0
}

const canEdit = (row) => {
  return ['draft', 'rejected'].includes(row.status)
}

const canApprove = (row) => {
  return row.status === 'pending'
}

const canDelete = (row) => {
  return ['draft', 'rejected'].includes(row.status)
}

// 页面加载
onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.contract-list-page {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.header-left h2 {
  margin: 0 0 10px 0;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 24px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 统计卡片 */
.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: white;
  margin-right: 15px;
  flex-shrink: 0;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 搜索卡片 */
.search-card {
  margin-bottom: 20px;
}

/* 表格卡片 */
.table-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 金额样式 */
.amount {
  font-weight: 600;
  color: #67c23a;
}

/* 危险文本 */
.text-danger {
  color: #f56c6c;
  font-weight: 600;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style>

